import { getUserInfo, setUserInfo } from "../../utils/storage"
import { getVipService } from '../../api/vipService/index' 
import { getCodeSession, GetCodeSessionDto } from '../../api/wxapi/index'
import { beVip } from '../../api/wxuser/index'
import config from '../../config/index'
import { addRechargeRecord } from '../../api/rechargeRecord/index'
import md5 from 'js-md5'
const dayjs = require("dayjs");
Page({
  data: {
    user: {} as WxUser,
    currentChoose: {} as ListVipService,
    currentDiscount: 0,
    currentBonusCoins: 0,
    _index: 0,
    defaultAva: '../../static/images/defult_user.png',
    configBaseUrl: config.BaseUrl + '/',
    list: [
    ] as ListVipService[],
  },
  compare(vipA: ListVipService, vipB: ListVipService): number{
    return vipA.day - vipB.day
  },
  async initData() {
    const res = await getVipService()
    const user = getUserInfo()
    if(res.statusCode === config.SUCCESS_CODE) {
      let vipList = res.data as ListVipService[]
      vipList.sort(this.compare)
      this.setData({
        user,
        list: vipList,
        currentChoose: vipList[0],
        currentDiscount: vipList[0].discount,
        currentBonusCoins: vipList[0].bonusCoins
      })
    }
    
  },
  onSubmit() {
    let that = this
    wx.login({
      success (res: any) {
        let data: GetCodeSessionDto = {
          appid: config.appid,
          secret: config.secret,
          js_code: res.code,
          grant_type: 'authorization_code'
        }
        getCodeSession(data).then((res: any) => {
          that.pay(res.data.openid)
        })
      }
    })
  },
  pay(openid: string) {
    let mchntCd = '0003050F5420999'
    let randomStr = Array(25).fill('').map(() => Math.random().toString(36).charAt(2)).join('');
    let length = 10; // 生成的字符串长度
    let randomNum = Math.random().toString().substr(2, length); // 生成全是数字的随机字符串
    let nowTime = dayjs().format('YYYYMMDDHHmmss')
    wx.request({
      url: 'https://aipay.fuioupay.com/aggregatePay/wxPreCreate',
      method: 'POST',
      data: {
        'version': '1.0',
        'mchnt_cd': mchntCd,
        'random_str': randomStr, 
        'order_type': 'WECHAT',
        'transaction_id': '',
        'user_id': '',
        'order_amt': String(this.data.currentChoose.price * 100),
        'settle_order_amt': String(this.data.currentChoose.price * 100),
        'curr_type': '',
        'mchnt_order_no': '11411' + randomNum,
        'product_id': '',
        'goods_des': '充值vip',
        'goods_detail': '',
        'txn_begin_ts': nowTime,
        'term_id': '2u32ir34',
        'goods_tag': '',
        'term_ip': '139.224.135.193',
        'addn_inf': '',
        'notify_url': 'https://aipaytest.fuioupay.com/aggregatePay/preCreate',
        'limit_pay': '',
        'trade_type': 'LETPAY',
        'openid': openid,
        'sub_openid': openid,
        'sub_appid': config.appid,
        'reserved_fy_term_id': '',
        'reserved_expire_minute': '',
        'reserved_user_creid': '',
        'reserved_user_truename': '',
        'reserved_user_mobile': '',
        'reserved_bxno_inf': '',
        'reserved_fy_term_type': '',
        'reserved_fy_term_sn': '',
        'reserved_device_info': '',
        'reserved_ali_extend_params': '',
        'sign': md5(`${mchntCd}|LETPAY|${String(this.data.currentChoose.price * 100)}|11411${randomNum}|${nowTime}|充值vip|2u32ir34|139.224.135.193|https://aipaytest.fuioupay.com/aggregatePay/preCreate|${randomStr}|1.0|cad07470c16511ed7c076197eeda9e44`),
        'reserved_terminal_info': ''
      },
      success: (res: any) => {
        if(res.data.result_code === '000000') {
          let timeStamp = res.data.sdk_timestamp
          let nonceStr = res.data.sdk_noncestr
          let packageStr = res.data.sdk_package
          let singTypeStr = res.data.sdk_signtype
          let paySignStr = res.data.sdk_paysign
          let merchantId = res.data.reserved_channel_order_id
          wx.requestPayment({
            timeStamp,
            nonceStr,
            package: packageStr,
            signType: singTypeStr,
            paySign: paySignStr,
            success: async () => {
              //支付成功后创建订单记录
              let recordData = {
                merchantId,
                phone: this.data.user.phone,
                details: `充值${this.data.currentChoose.day}天会员`,
                price: this.data.currentChoose.price,
                orderTime: dayjs.unix(timeStamp).format('YYYY-MM-DD HH:mm:ss')
              } as RechargeRecord
              //创建订单记录
              const recordRes = await addRechargeRecord(recordData)
              if(recordRes.statusCode === config.CREATED_CODE) {
                let data = {
                  id: this.data.currentChoose.id as string,
                  day: this.data.currentChoose.day,
                  discount: this.data.currentChoose.discount,
                  bonusCoins: this.data.currentChoose.bonusCoins
                }
                //订单记录成功后开通vip
                const payRes = await beVip(this.data.user.id, data)
                if(payRes.statusCode === config.CREATED_CODE) {
                  wx.showToast({title: '开通成功', icon: 'success'})
                  setUserInfo(payRes.data)
                  setTimeout(() => {
                    wx.reLaunch({
                      url: '/pages/me/me'
                    })
                  }, 1000)
                } else {
                  wx.showToast({title: '开通失败', icon: 'error'})
                }
              }
            },
            fail: () => {
              wx.showToast({title: '支付失败', icon: 'none'})
            },
            complete: () => {
            }
          })
        }
      }
    })
  },
  chooseMeal(e: any) {
    this.setData({
      currentChoose: e.currentTarget.dataset.item,
      currentDiscount: e.currentTarget.dataset.item.discount,
      currentBonusCoins: e.currentTarget.dataset.item.bonusCoins,
      _index: e.currentTarget.dataset.index
    })
  },
  toProtocol() {
    wx.downloadFile({
      url: config.BaseUrl + '/files/protocol.pdf',
      success: (res) => {
        wx.openDocument({
          filePath: res.tempFilePath
        })
      } 
    })
  },
  onLoad() {
    this.initData()
  },
})